﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace EncircleFTM
{
    public class InstallEchoPrinter
    {
        #region "Member variables"
        private const string STR_PRINTERNAME = "ECHO";
        private const string STR_PORTNAME = "XPSport:";
        private const string DRIVER_NAME = "Microsoft XPS Document Writer";
        private const string PRINT_PROCESSOR = "WinPrint";
        #endregion

        #region "PInvokes"
        [DllImport("KERNEL32.dll")]
        static extern void ZeroMemory(ref PRINTER_INFO_2 pPrinter, int length);

        [DllImport("winspool.drv", CharSet = CharSet.Auto)]
        static extern int AddPrinter(string pName, uint Level, [In] ref PRINTER_INFO_2 pPrinter);

        [DllImport("winspool.drv")]
        static extern int ClosePrinter(int hPrinter);

        [DllImport("kernel32.dll")]
        private static extern int GetLastError();

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        struct PRINTER_INFO_2
        {
            public string pServerName,
            pPrinterName,
            pShareName,
            pPortName,
            pDriverName,
            pComment,
            pLocation;
            public IntPtr pDevMode;
            public string pSepFile,
            pPrintProcessor,
            pDatatype,
            pParameters;
            public IntPtr pSecurityDescriptor;
            public uint Attributes,
            Priority,
            DefaultPriority,
            StartTime,
            UntilTime,
            Status,
            cJobs,
            AveragePPM;
        }
        #endregion

        public static void installPrinter()
        {
            InstallEchoPrinter printer = new InstallEchoPrinter();
            printer.AddECHOPrinter();
        }

        private void AddECHOPrinter()
        {
            try
            {
                PRINTER_INFO_2 pi2 = new PRINTER_INFO_2();
                int hPrinter;
                int herror;
                ZeroMemory(ref pi2, Marshal.SizeOf(pi2));
                pi2.pPrinterName = STR_PRINTERNAME;
                pi2.pPortName = STR_PORTNAME;
                pi2.pDriverName = DRIVER_NAME;
                pi2.pPrintProcessor = PRINT_PROCESSOR;
                hPrinter = AddPrinter("", 2, ref pi2);
                if (hPrinter == 0)
                {
                    herror = GetLastError();
                }
                ClosePrinter(hPrinter);

            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.Message);
            }
        }
    }
}
